package com.wanshi.servlet;

import com.alibaba.fastjson.JSON;
import com.wanshi.entity.Result;
import com.wanshi.entity.User;
import com.wanshi.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cunzai")
public class cunzai extends HttpServlet {

	//2 查询用户是否存在
	UserService userService = new UserService();
	public static final String NAME_AND_PSD = "^\\w{4,20}$";

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//1 获取用户名
		String username = request.getParameter("username");
		Result result = new Result();
		if(!username.matches(NAME_AND_PSD) ){
			result.setMessage("用户名格式不正确,必须是4-20位字母数字或下划线组成");
			response.getWriter().write(JSON.toJSONString(result));
			return;
		}


		User user = userService.findUserByName(username);
		//3 告诉前端ajax请求

		if(user == null){
			result.setMessage("该用户名可以使用");
		}else{
			result.setMessage("该用户名已经存在");
		}
		response.getWriter().write(JSON.toJSONString(result));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}